

const path = require('path');
const Koa = require('koa');
const app = new Koa();
const bodyParser = require('koa-bodyparser');
const cors = require('koa2-cors');

const Router = require('koa-router');
const router = new Router();

let dblogic = require('./dblogic');
let G = require('./config');

const apis = require('./apis');

const VERSION = 1;

function apiUrl(p){
    let str =  path.join('/api',`v${VERSION}`,p);
    console.log("str:",str);
    return str.replace(/\\/g,"/");
}

// 路由
router.post(apiUrl(apis.USER_LOGIN),async (ctx)=>{
    let obj = ctx.request.body;
    if(obj && obj.username && obj.password){
        let uname = obj.username;
        let pwd = obj.password;
        G.log(uname, pwd);

        // 判断用户是否存在
        let row = await dblogic.login(uname,pwd);
        G.log('row:',row);
        if(row){
            // 还要查出此用户的所有账户信息(暂时不需要分页)
            // let key = row.key;
            let lstInfo = await dblogic.getInfos(row.uuid);
            G.log('lstInfo:',lstInfo);
            ctx.body = {
                uname:row.uname,
                uuid:row.uuid,
                rows:lstInfo,
                key:row.key
            };
        }else{
            // 账户验证错误
            ctx.body = {
                err:1,
                msg:'用户名或密码错误!'
            };
        }
    }else{
        ctx.body = {
            err:1,
            msg:'未知错误!'
        };
    }
});

router.post(apiUrl(apis.USER_CREATE),async (ctx,next)=>{
    let obj = ctx.request.body;
    let ret = await dblogic.newUser({
        uname:obj.username,
        pwd:obj.password,
        key:obj.key,
    });
    if(!ret){
        ctx.body = {
            err:1,
            msg:'用户名已存在'
        }
    }else{
        // 创建成功
        ctx.body = {
            err:0
        }
    }
});

// 查询密码
// 需要根据原来用户注册时使用的key去解密.
router.post(apiUrl(apis.ITEM_QUERY),async (ctx)=>{
    let obj = ctx.request.body;
    // let md5Key = obj.md5Key;
    let key = obj.key;
    let encryptPwd = obj.pwd;
    ctx.body = {
        pwd:G.decrypt(encryptPwd,key),
    }
});

router.post(apiUrl(apis.ITEM_ADD),async (ctx)=>{
    let obj = ctx.request.body;
    let newRow = await dblogic.newInfo({
        uname:obj.username,
        pwd:obj.password,
        desc:obj.desc,
        email:obj.email,
        uuid:obj.uuid,
        key:obj.key
    });
    if(newRow){
        ctx.body = {
            err:0,
            newRow:newRow
        }
    }else{
         console.error('好像出现了问题...!');
         ctx.body = {
             err:1,
             msg:'好像出现了问题'
         }
    }
});

router.post(apiUrl(apis.ITEM_DELETE),async (ctx)=>{
    let obj = ctx.request.body;
    await dblogic.deleteInfo(obj);
    // TODO: 异常如何处理比较好???
    ctx.body = {
        err:0
    }
});

router.get("/api/v1/xx",async (ctx)=>{
    console.log("hello world!");
    ctx.body = {
        name:'zhangsan'
    };
});

////------------
// middle
app.use(cors());
app.use(bodyParser());
app.use(router.routes()).use(router.allowedMethods());

async function start() {
    G.initEnv();
    await dblogic.initDb();
    app.listen(3001,()=>{
        console.log('server is running at http://localhost:3001');
    });
}

start();


